﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Runda.EShop.Common.Utility;
using Runda.EShop.Common.Entity;
using Runda.EShop.Dal;
using System.Data;

namespace Runda.EShop.Bll
{
    public class SystemBll:BllBase
    {
        #region Field and Property

        private string CacheName_GetAllUser = "GetAllUser";
        private string CacheName_GetUserHavedFunction = "GetUserHavedFunction";

        private string CacheName_GetAllFunction = "GetAllFunction";
        private string CacheName_GetAlllPageInfo = "GetAllPageInfo";
        #endregion

        #region Constructor

        public SystemBll()
        {
            _cacheName = "SystemCacheManager";
        }
        #endregion

        #region User Bussiness

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="OldPassword">加密后的旧密码</param>
        /// <param name="NewPassword"></param>
        /// <returns></returns>
        public OperateResult ChangePassword(Guid UserID, string OldPassword, string NewPassword)
        {
            OperateResult result = new OperateResult();

            SysUserEntity entity = GetUserEntityFromCache(UserID);
            //检查旧密码是否相同
            if (entity.Password != OldPassword)
            {
                result.IsSuccess = false;
                result.Message = "旧密码不正确!";
                return result;
            }
            SysUserDal dal = new SysUserDal();
            try
            {
                dal.UpdatePassword(UserID, NewPassword);
                base.Flush();
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = "保存过程中发生错误!";
                throw;
            }
            return result;
        }

        /// <summary>
        /// 管理员修改密码
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="NewPassword"></param>
        /// <returns></returns>
        public OperateResult ChangePassword(Guid UserID, string NewPassword)
        {
            OperateResult result = new OperateResult();
            SysUserDal dal = new SysUserDal();
            try
            {
                dal.UpdatePassword(UserID, NewPassword);
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = "保存过程中发生错误!";
            }
            return result;
        }

        public SysUserEntity GetUserEntityFromCache(Guid UserID)
        {
            if (base.ExistsCacheData(CacheName_GetAllUser))
            {
                List<SysUserEntity> list = null;
                list = GetCacheData(CacheName_GetAllUser) as List<SysUserEntity>;

                return list.Find(delegate(SysUserEntity e) { return e.UserID == UserID; });
            }
            else
            {
                SysUserDal dal = new SysUserDal();
                List<SysUserEntity> list = dal.GetAll<SysUserEntity>(" and Deleted = 0");

                AddCache(CacheName_GetAllUser, list);

                return list.Find(delegate(SysUserEntity e) { return e.UserID == UserID; });
            }
        }

        /// <summary>
        /// 保存用户信息以及该用户的角色列表
        /// </summary>
        /// <param name="entity"></param>
        public void SaveUser(SysUserEntity entity)
        {
            SysUserDal UserDal = new SysUserDal();
            SysUserRoleRelationDal UserRoleDal = new SysUserRoleRelationDal();

            using (var tran = new System.Transactions.TransactionScope())
            {
                UserDal.InsertOrUpdate(entity);

                if (entity.UserRoleRelationList != null)
                {
                    //角色
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "UserID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@UserID"; parm.ParameterValue = entity.UserID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    UserRoleDal.Delete<SysUserRoleRelationEntity>(parms);
                    foreach (SysUserRoleRelationEntity UserRoleEntity in entity.UserRoleRelationList)
                    {
                        UserRoleDal.Insert(UserRoleEntity);
                    }

                }

                tran.Complete(); 
            }

            base.Flush();
        }
        #endregion

        #region Role Bussiness
        /// <summary>
        /// 保存角色信息以及该角色的权限列表
        /// </summary>
        /// <param name="entity"></param>
        public void SaveRole(SysRoleEntity entity)
        {
            SysRoleDal RoldDal = new SysRoleDal();
            SysRoleFunctionRelationDal RoleFunDal = new SysRoleFunctionRelationDal();

            using (var tran = new System.Transactions.TransactionScope())
            {
                RoldDal.InsertOrUpdate(entity);

                if (entity.RoleFunctionRelateList != null)
                {
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "RoleID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@RoleID"; parm.ParameterValue = entity.RoleID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    RoleFunDal.Delete<SysRoleFunctionRelationEntity>(parms);
                    foreach (SysRoleFunctionRelationEntity RoleFunEntity in entity.RoleFunctionRelateList)
                    {
                        RoleFunDal.Insert(RoleFunEntity);
                    }
                }
                tran.Complete();
            }

            base.Flush();
        }

        public void DeleteRole(Guid RoleID)
        {
            using (System.Transactions.TransactionScope tran = new System.Transactions.TransactionScope())
            {
                this.Delete<SysRoleFunctionRelationEntity>(" and RoleID = '" + RoleID + "'");

                this.Delete<SysUserRoleRelationEntity>(" and RoleID = '" + RoleID + "'");

                this.Delete<SysRoleEntity>(" and RoleID = '" + RoleID + "'");

                tran.Complete();
            }
        }
        #endregion

        #region Function Bussiness
        /// <summary>
        /// 根据角色构造功能点树
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public DataTable BuildAllFunction(Guid RoleID)
        {
            SysFunctionDal dal = new SysFunctionDal();
            return dal.BuildAllFunction(RoleID);
        }

        /// <summary>
        /// 检查用户是否具有某权限
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="CheckType">0: by URL,  1: by FunctionCode </param>
        /// <param name="CheckObject">Url or FunctionCode</param>
        /// <returns></returns>
        public bool CheckUserHasFuction(Guid UserID, int CheckType, string CheckObject)
        {
            if (base.ExistsCacheData(CacheName_GetUserHavedFunction))
            {
                List<SysFunctionEntity> List = GetCacheData(CacheName_GetUserHavedFunction) as List<SysFunctionEntity>;
                if (CheckType == 0)
                {
                    return List.Exists(delegate(SysFunctionEntity entity) { return entity.URL.ToLower() == CheckObject.ToLower() && entity.UserID == UserID; });
                }
                else
                {
                    return List.Exists(delegate(SysFunctionEntity entity) { return entity.FuncID.ToLower() == CheckObject.ToLower() && entity.UserID == UserID; });
                }
            }
            else
            {
                SysFunctionDal FunDal = new SysFunctionDal();
                if (base.IsCacheUsed)
                {
                    DataTable dt = new DataTable();
                    dt = FunDal.LoadUserAllFunction();
                    base.AddCache(CacheName_GetUserHavedFunction, BuildEntityListFromDataTable<SysFunctionEntity>(dt));
                }

                List<SysFunctionEntity> Funcs = FunDal.LoadUserHavedFunction(UserID);
                if (CheckType == 0)
                {
                    return Funcs.Exists(delegate(SysFunctionEntity entity) { return entity.URL.ToLower() == CheckObject.ToLower(); });
                }
                else
                {
                    return Funcs.Exists(delegate(SysFunctionEntity entity) { return entity.FuncID.ToLower() == CheckObject.ToLower(); });
                }
            }
        }

        public List<SysFunctionEntity> LoadAllFunction()
        {
            if (base.ExistsCacheData(CacheName_GetAllFunction))
            {
                return GetCacheData(CacheName_GetAllFunction) as List<SysFunctionEntity>;
            }
            else
            {
                SysFunctionDal dal = new SysFunctionDal();
                List<SysFunctionEntity> list = BuildEntityListFromDataTable<SysFunctionEntity>(dal.LoadAllFunctionWithPath());

                AddCache(CacheName_GetAllFunction, list);

                return list;
            }
        }

        public SysFunctionEntity GetFunctionWithPath(string FuncID)
        {
            List<SysFunctionEntity> list = LoadAllFunction();
            return list.Find(fun => fun.FuncID == FuncID);
        }

        public SysFunctionEntity GetFunctionWithByUrl(string URL)
        {
            List<SysFunctionEntity> list = LoadAllFunction();
            return list.Find(fun => fun.URL.ToLower() == URL.ToLower());
        }

        /// <summary>
        /// 获取功能点树数据
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<SysFunctionEntity> LoadFunctionEntitiesByUserIDFromCache(Guid UserID)
        {
            if (base.ExistsCacheData(CacheName_GetUserHavedFunction))
            {
                List<SysFunctionEntity> List = GetCacheData(CacheName_GetUserHavedFunction) as List<SysFunctionEntity>;
                return List.FindAll(delegate(SysFunctionEntity ent) { return ent.UserID == UserID; });
            }
            else
            {
                SysFunctionDal dal = new SysFunctionDal();
                DataTable dt = null;
                dt = dal.LoadUserAllFunction();
                base.AddCache(CacheName_GetUserHavedFunction, BuildEntityListFromDataTable<SysFunctionEntity>(dt));

                return BuildEntityListFromDataTable<SysFunctionEntity>(dt);
            }
        }
        #endregion

        #region PageInfo
        public List<SysPageInfoEntity> LoadAllPageInfo()
        {
            if (base.ExistsCacheData(CacheName_GetAlllPageInfo))
            {
                return GetCacheData(CacheName_GetAlllPageInfo) as List<SysPageInfoEntity>;
            }
            else
            {
                SysPageInfoDal dal = new SysPageInfoDal();
                List<SysPageInfoEntity> list = BuildEntityListFromDataTable<SysPageInfoEntity>(dal.LoadAllFunctionWithPath());

                AddCache(CacheName_GetAlllPageInfo, list);

                return list;
            }
        }

        public SysPageInfoEntity GetPageInfoWithByUrl(string URL)
        {
            List<SysPageInfoEntity> list = LoadAllPageInfo();
            return list.Find(fun => fun.URL.ToLower() == URL.ToLower());
        }
        #endregion

        #region Cache
        public void CacheClear()
        {
            this.Flush(); 
        }  
        #endregion

    }
}
